package darknet.core.impl.friend;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import darknet.core.spec.friend.Friend;


/**
 * Implementation of a friend.
 * 
 * @author yoyo
 */
public class FriendImpl implements Friend {
    
    /** The name of the friend. */
    private String name;
    
    /** The certificate of the friend. */
    private Certificate certificate;
    
    /**
     * Initialise a new friend.
     * 
     * @param name	  The name of the friend.
     * @param certificate The path to the X509 certificate file.
     * 
     * @throws FileNotFoundException is throw if certificate is not found.
     */
    public FriendImpl(String name, File certificate) 
    throws FileNotFoundException {
	
	// Check parameters.
	if (name == null || name.length() == 0) {
	    throw new IllegalArgumentException("name is invalid");
	}
	
	if (certificate == null) {
	    throw new IllegalArgumentException("certificate is invalid");
	}
	
	// Generate a certificate.
	Certificate cert = null;
	try {
	    CertificateFactory fact = CertificateFactory.getInstance("X.509");
	    cert = fact.generateCertificate(
		    new FileInputStream(certificate));
	} catch (CertificateException e) {
	    throw new Error("Your JVM don't support X.509 CertificateFactory");
	}
	
	this.name = name;
	this.certificate = cert;
    }
    
    public FriendImpl(String name, Certificate certificate) {
	
	// Check parameters.
	if (name == null || name.length() == 0) {
	    throw new IllegalArgumentException("name is invalid");
	}
	
	if (certificate == null) {
	    throw new IllegalArgumentException("certificate is invalid");
	}
	
	this.name = name;
	this.certificate = certificate;
    }

    @Override
    public Certificate getCertificate() {
	return certificate;
    }

    @Override
    public String getName() {
	return name;
    }
}
